from playwright.sync_api import sync_playwright

from common.playwright_driver import P_Driver
from common.utils import get_after_date_str
from repository.idrs_db import update_status_url_to_idrs, update_status_to_idrs


def idrs_flow(idrs_dict: dict):
    idrs_url = r"http://aed.cnpdc.com/AED/Flow/NWBIDRS/WBIDRS.aspx?modi=add&ReUrl=http://aed.cnpdc.com/Common/AED_WorkFlow/AED_NewDraft_List.aspx"
    with sync_playwright() as p:
        browser = p.chromium.launch(headless=False)
        page = browser.new_page()

        p_driver = P_Driver()
        p_driver.page = page
        # 打开页面
        p_driver.open_url_whit_token(idrs_url)
        p_driver.check_load("#kbkidrs")
        file_channel = idrs_dict["file_channel"]
        # 技术信息添加
        page.select_option("#Doc_SecClass_txt1", "无密级")
        page.fill("#Bas_Name_txt1", idrs_dict["title"])

        # 选择项目
        page.fill("#Bas_PrjCode_txt1", idrs_dict["project_code"])
        page.click("Bas_PrjCode_txt1")
        page.click(f'//div[@dataid="{idrs_dict["project_code"]}"]')

        # 选择参与方
        page.fill("#ToSect_prt1", idrs_dict["assister"])
        page.click("#ToSect_prt1")
        page.click(f'//div[@dataid="{idrs_dict["assister"]}"]')

        page.click("#_easyui_textbox_input3")

        el = page.locator(
            f'//div[@class="combo-panel panel-body panel-body-noheader"]/div[contains(text(),"{idrs_dict["department"]}")]')
        if el.count():
            el.focus()
            el.click()

        page.fill('#_easyui_textbox_input2', get_after_date_str())
        page.fill('#HuiWenHao_txt1', file_channel)
        page.evaluate("MyService('add')")
        url = page.url
        status = 1
        if not file_channel:
            status = 2
        update_status_url_to_idrs(status, url, idrs_dict["id"])

        if file_channel:
            # 添加文件
            add_file_xpath = '//div[@class="datagrid-wrap panel-body"]//a//span[text()="文件清单"]'
            p_driver.check_load(add_file_xpath)
            page.click(add_file_xpath)
            p_driver.check_load("#addfile")
            page.frame_locator("#frmDialogaddfile").locator("#txtHJCode").fill(file_channel)
            page.evaluate("return queryFile('');")
            # page.frame_locator("#frmDialogaddfile").locator("#btnSearch").click()
            page.frame_locator("#frmDialogaddfile").locator("#ckboxs").click()
            page.click('//div[@class="dialog-button"]/a//span[text()="保存"]')
            page.evaluate("MyService('edit')")
            update_status_to_idrs(2, idrs_dict["id"])

        attachment_list = idrs_dict["sys_attachment"].strip().split(",")
        if attachment_list:
            page.locator('//div[@class="tabs-header tabs-header-plain"]//a//span[text()="附件信息"]').click()

        return "创建IDRS成功"
